import cv2
import numpy as np
import sys
import os
import time

def get_available_cameras():
    """获取系统中可用的摄像头设备"""
    available_cameras = []
    for i in range(10):
        device_path = f'/dev/video{i}'
        if os.path.exists(device_path):
            try:
                # 检查设备权限
                mode = os.stat(device_path).st_mode
                print(f"设备 {device_path} 权限: {oct(mode)}")
                available_cameras.append(device_path)
            except Exception as e:
                print(f"检查设备 {device_path} 时出错: {str(e)}")
    return available_cameras

def test_camera():
    available_cameras = get_available_cameras()
    print(f"发现以下摄像头设备: {available_cameras}")
    
    for device in available_cameras:
        print(f"\n尝试打开摄像头设备: {device}")
        
        # 尝试不同的API后端
        backends = [cv2.CAP_V4L2, cv2.CAP_V4L]
        for backend in backends:
            print(f"尝试使用后端: {backend}")
            cap = cv2.VideoCapture(device, backend)
            
            if not cap.isOpened():
                print(f"无法使用后端 {backend} 打开设备 {device}")
                continue
                
            try:
                # 设置摄像头参数
                cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
                cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
                
                # 打印摄像头的实际参数
                width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
                height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
                fps = cap.get(cv2.CAP_PROP_FPS)
                print(f"摄像头参数: {width}x{height} @ {fps}fps")
                
                # 尝试多次读取画面
                for i in range(3):
                    ret, frame = cap.read()
                    if ret:
                        print(f"成功读取第 {i+1} 帧，大小: {frame.shape}")
                        
                        while True:
                            ret, frame = cap.read()
                            if not ret:
                                print("读取画面失败")
                                break
                                
                            # 显示帧率
                            cv2.putText(frame, f"FPS: {fps:.1f}", (10, 30),
                                      cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
                            
                            cv2.imshow("capture", frame)
                            if cv2.waitKey(1) & 0xFF == ord('q'):
                                break
                                
                        cap.release()
                        cv2.destroyAllWindows()
                        return True
                    else:
                        print(f"第 {i+1} 次读取失败")
                        time.sleep(1)  # 等待一秒再试
                        
            except Exception as e:
                print(f"发生错误: {str(e)}")
            finally:
                cap.release()
                
    return False

if __name__ == "__main__":
    print("系统信息:")
    print(f"OpenCV版本: {cv2.__version__}")
    print(f"当前用户: {os.getuid()}")
    print(f"当前用户组: {os.getgroups()}")
    print(f"当前进程权限: {oct(os.getuid())}")
    
    if not test_camera():
        print("\n未能成功打开任何摄像头")
        print("请检查:")
        print("1. 摄像头是否正确连接")
        print("2. 设备权限是否正确（应该是666或660）")
        print("3. 当前用户是否在video组中")
        print("4. 尝试重新插拔摄像头")

